package com.zj.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zj.dao.OrderDetailMapper;
import com.zj.model.Orderdetail;
import com.zj.restApi.IdGenratorApi;
import com.zj.web.bean.OrderdetailDTO;
import com.zj.web.bean.ResponseResult;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Log
public class OrderdetailServiceImpl extends ServiceImpl<OrderDetailMapper, Orderdetail> implements OrderdetailService{
    private final OrderDetailMapper orderDetailMapper;
    private final IdGenratorApi idGenratorApi;

    @Override
    @Transactional // 添加事务管理
    public boolean addOrderDetail(Long orderId, List<OrderdetailDTO> detailList) {
        if (orderId == null || detailList == null || detailList.isEmpty()) {
            throw new IllegalArgumentException("参数不能为空");
        }
        // DTO转Entity
        List<Orderdetail> entities = detailList.stream()
                .map(dto -> {
                    //1.调用 idGenerator 服务 取出id号
                    ResponseEntity<ResponseResult<Long>> responseEntity = idGenratorApi.getNextId();  //jdk动态代理对象
                    if(responseEntity.getStatusCode()!= HttpStatus.OK || responseEntity.getBody()==null){
                        throw new RuntimeException("调用idGenerator服务失败");
                    }
                    ResponseResult<Long> responseResult = responseEntity.getBody();
                    log.info(responseResult.toString());
                    if (responseResult == null || responseResult.getCode() != 1) {
                        throw new RuntimeException("调用idGenerator服务失败");
                    }
                    Long id = responseResult.getData();
                    dto.setDetailId(id);
                    dto.setOrderId(orderId);
                    //2.属性拷贝
                    Orderdetail detail = new Orderdetail();
                    BeanUtils.copyProperties(dto,detail);
                    return detail;
                })
                .collect(Collectors.toList());

        // 批量插入
        boolean b = saveBatch(entities);
        if(!b){
            throw new RuntimeException("批量插入失败");
        }
        return true;
    }

    //根据订单id查询订单详情
    @Override
    public List<OrderdetailDTO> getOrderDetailByIds(List<Integer> ids) {
        List<Orderdetail> orderdetails = baseMapper.selectBatchIds(ids);
        return orderdetails.stream().map(orderdetail -> {
            OrderdetailDTO orderdetailDTO = new OrderdetailDTO();
            BeanUtils.copyProperties(orderdetail,orderdetailDTO);
            return orderdetailDTO;
        }).collect(Collectors.toList());
    }





}
